<?php
/**
 * 考勤管理系统卸载程序
 * 用于删除数据库表和清理配置文件
 */

// 检查是否已安装
if (!file_exists(__DIR__ . '/config.inc.php')) {
    die('系统未安装，无需卸载。');
}

$results = [];
$successCount = 0;
$errorCount = 0;

if ($_POST && $_POST['action'] === 'uninstall') {
    try {
        // 加载配置
        $config = include __DIR__ . '/config.inc.php';
        $db_config = $config['db'];
        
        // 连接数据库
        $dsn = "mysql:host={$db_config['host']};dbname={$db_config['database']};charset={$db_config['charset']}";
        $pdo = new PDO($dsn, $db_config['username'], $db_config['password']);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $results[] = ['type' => 'success', 'message' => '数据库连接成功！'];
        
        // 要删除的表列表
        $tables = [
            'users',
            'attendance_records', 
            'system_config',
            'overtime_records',
            'leave_records',
            'business_trips'
        ];
        
        // 删除表
        foreach ($tables as $table) {
            try {
                $pdo->exec("DROP TABLE IF EXISTS `{$table}`");
                $results[] = ['type' => 'success', 'message' => "删除表成功: {$table}"];
                $successCount++;
            } catch (Exception $e) {
                $results[] = ['type' => 'error', 'message' => "删除表失败 {$table}: " . $e->getMessage()];
                $errorCount++;
            }
        }
        
        // 删除配置文件
        if (file_exists(__DIR__ . '/config.inc.php')) {
            if (unlink(__DIR__ . '/config.inc.php')) {
                $results[] = ['type' => 'success', 'message' => '删除配置文件成功'];
                $successCount++;
            } else {
                $results[] = ['type' => 'error', 'message' => '删除配置文件失败'];
                $errorCount++;
            }
        }
        
        // 删除安装目录（如果存在）
        if (file_exists(__DIR__ . '/install')) {
            if (deleteDirectory(__DIR__ . '/install')) {
                $results[] = ['type' => 'success', 'message' => '删除安装目录成功'];
                $successCount++;
            } else {
                $results[] = ['type' => 'error', 'message' => '删除安装目录失败'];
                $errorCount++;
            }
        }
        
    } catch (PDOException $e) {
        $results[] = ['type' => 'error', 'message' => '数据库连接失败: ' . $e->getMessage()];
        $errorCount++;
    }
}

/**
 * 递归删除目录
 */
function deleteDirectory($dir) {
    if (!file_exists($dir)) {
        return true;
    }
    
    if (!is_dir($dir)) {
        return unlink($dir);
    }
    
    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }
        
        if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
            return false;
        }
    }
    
    return rmdir($dir);
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考勤管理系统 - 卸载程序</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .uninstall-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
            max-width: 800px;
            margin: 0 auto;
        }
        .uninstall-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem;
            text-align: center;
        }
        .uninstall-body {
            padding: 2rem;
        }
        .result-item {
            padding: 10px;
            margin: 5px 0;
            border-radius: 5px;
        }
        .result-success {
            background-color: #d4edda;
            border-left: 4px solid #28a745;
        }
        .result-error {
            background-color: #f8d7da;
            border-left: 4px solid #dc3545;
        }
        .warning-box {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 5px;
            padding: 15px;
            margin: 20px 0;
        }
    </style>
</head>
<body>
    <div class="uninstall-container">
        <div class="uninstall-header">
            <h1><i class="fas fa-clock me-2"></i>考勤管理系统</h1>
            <p class="mb-0">卸载程序</p>
        </div>
        
        <div class="uninstall-body">
            <h3 class="mb-4">系统卸载</h3>
            
            <?php if (empty($results)): ?>
                <div class="warning-box">
                    <h5><i class="fas fa-exclamation-triangle me-2"></i>警告</h5>
                    <p><strong>此操作不可逆！</strong> 卸载将执行以下操作：</p>
                    <ul>
                        <li>删除所有数据库表（用户表、考勤记录表等）</li>
                        <li>删除系统配置文件</li>
                        <li>删除安装目录</li>
                        <li><strong>所有数据将永久丢失！</strong></li>
                    </ul>
                    <p class="mb-0">请在继续之前确保已备份重要数据。</p>
                </div>
                
                <form method="post">
                    <input type="hidden" name="action" value="uninstall">
                    <div class="mb-3">
                        <label for="confirm" class="form-label">确认卸载</label>
                        <input type="text" class="form-control" id="confirm" name="confirm" 
                               placeholder="请输入 '确认卸载' 以继续" required>
                        <div class="form-text">请输入 "确认卸载" 来确认您要卸载系统</div>
                    </div>
                    
                    <div class="text-center">
                        <button type="submit" class="btn btn-danger btn-lg" 
                                onclick="return confirm('确定要卸载系统吗？此操作不可逆！')">
                            <i class="fas fa-trash me-2"></i>确认卸载
                        </button>
                    </div>
                </form>
            <?php else: ?>
                <div class="mb-4">
                    <h5>卸载结果：</h5>
                    <?php foreach ($results as $result): ?>
                        <div class="result-item <?php echo $result['type'] === 'success' ? 'result-success' : 'result-error'; ?>">
                            <?php if ($result['type'] === 'success'): ?>
                                <i class="fas fa-check text-success me-2"></i>
                            <?php else: ?>
                                <i class="fas fa-times text-danger me-2"></i>
                            <?php endif; ?>
                            <?php echo $result['message']; ?>
                        </div>
                    <?php endforeach; ?>
                    
                    <div class="mt-3">
                        <h5>卸载统计：</h5>
                        <p>成功: <span class="text-success"><?php echo $successCount; ?></span> 条</p>
                        <p>失败: <span class="text-danger"><?php echo $errorCount; ?></span> 条</p>
                    </div>
                    
                    <?php if ($errorCount === 0): ?>
                        <div class="alert alert-success mt-3">
                            <h5><i class="fas fa-check-circle me-2"></i>卸载成功！</h5>
                            <p class="mb-0">系统已成功卸载，所有数据已清理。</p>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-warning mt-3">
                            <h5><i class="fas fa-exclamation-triangle me-2"></i>卸载过程中出现错误</h5>
                            <p class="mb-0">部分操作失败，请检查错误信息。</p>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/js/all.min.js"></script>
    
    <script>
        // 确认卸载验证
        document.querySelector('form').addEventListener('submit', function(e) {
            var confirmInput = document.getElementById('confirm');
            if (confirmInput.value !== '确认卸载') {
                e.preventDefault();
                alert('请输入 "确认卸载" 来确认卸载操作');
                confirmInput.focus();
            }
        });
    </script>
</body>
</html>
